<template>
  <div class="real-time-panel" v-loading="loading">
    <div class="panel-header">
      <h2>
        <el-icon :size="20" style="margin-right: 6px;"><Monitor /></el-icon>
        实时数据
      </h2>
      <div class="header-actions">
        <el-button v-if="isFullscreen" type="primary" size="small" @click="exitFullscreen">
          <el-icon><Close /></el-icon>
          退出全屏
        </el-button>
      </div>
    </div>
    <div class="data-grid">
      <!-- 油井运行数据 -->
      <div class="data-group">
        <div class="group-header">
          <el-icon><Odometer /></el-icon>
          <span class="group-title">油井运行数据</span>
        </div>
        <div class="data-items">
          <div v-for="item in oilWellData" :key="item.label" class="data-item">
            <el-icon :size="20" :color="item.color"><component :is="item.icon" /></el-icon>
            <div class="item-content">
              <div class="item-label">{{ item.label }}</div>
              <div class="item-value">{{ item.value }} <span class="unit">{{ item.unit }}</span></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 变频数据 -->
      <div class="data-group">
        <div class="group-header">
          <el-icon><TrendCharts /></el-icon>
          <span class="group-title">变频数据</span>
        </div>
        <div class="data-items">
          <div v-for="item in frequencyData" :key="item.label" class="data-item">
            <el-icon :size="20" :color="item.color"><component :is="item.icon" /></el-icon>
            <div class="item-content">
              <div class="item-label">{{ item.label }}</div>
              <div class="item-value">{{ item.value }} <span class="unit">{{ item.unit }}</span></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 抽油机数据 -->
      <div class="data-group">
        <div class="group-header">
          <el-icon><Timer /></el-icon>
          <span class="group-title">抽油机数据</span>
        </div>
        <div class="data-items">
          <div v-for="item in pumpingUnitData" :key="item.label" class="data-item">
            <el-icon :size="20" :color="item.color"><component :is="item.icon" /></el-icon>
            <div class="item-content">
              <div class="item-label">{{ item.label }}</div>
              <div class="item-value">{{ item.value }} <span class="unit">{{ item.unit }}</span></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 控制参数 -->
      <div class="data-group">
        <div class="group-header">
          <el-icon><Box /></el-icon>
          <span class="group-title">控制参数</span>
        </div>
        <div class="data-items">
          <div v-for="item in pumpingControlData" :key="item.label" class="data-item">
            <el-icon :size="20" :color="item.color"><component :is="item.icon" /></el-icon>
            <div class="item-content">
              <div class="item-label">{{ item.label }}</div>
              <div class="item-value">{{ item.value }} <span class="unit">{{ item.unit }}</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useDeviceStore } from '@/stores/device'
import { updateDeviceOnlineStatus } from '@/api/device'
import {
  Odometer,
  TrendCharts,
  Timer,
  Box,
  Monitor,
  Close
} from '@element-plus/icons-vue'

const deviceStore = useDeviceStore()
const { currentDevice } = storeToRefs(deviceStore)

// 加载状态
const loading = ref(false)
const isFullscreen = ref(false)

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 退出全屏
const exitFullscreen = async () => {
  try {
    await document.exitFullscreen()
  } catch (err) {
    ElMessage.error('退出全屏失败')
  }
}

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})

// 定时器引用
let dataUpdateTimer = null

// 清除所有数据
const clearAllData = () => {
  oilWellData.value = oilWellData.value.map(item => ({
    ...item,
    value: '0.0'
  }))
  
  frequencyData.value = frequencyData.value.map(item => ({
    ...item,
    value: '0.0'
  }))
  
  pumpingUnitData.value = pumpingUnitData.value.map(item => ({
    ...item,
    value: '无数据'
  }))
  
  pumpingControlData.value = pumpingControlData.value.map(item => ({
    ...item,
    value: '0.0'
  }))
}

// 上次请求时间戳
let lastFetchTime = 0;

// 开始定时更新数据
const startDataUpdate = () => {
  // 先清除可能存在的定时器
  stopDataUpdate()
  
  // 立即获取一次数据
  fetchDeviceData()
  
  // 设置定时器，每180秒更新一次数据，显著减少API请求频率
  dataUpdateTimer = setInterval(fetchDeviceData, 180000)
}

// 停止定时更新数据
const stopDataUpdate = () => {
  if (dataUpdateTimer) {
    clearInterval(dataUpdateTimer)
    dataUpdateTimer = null
  }
}

// 获取设备数据
const fetchDeviceData = async () => {
  if (!currentDevice.value) {
    console.warn('没有选中设备，无法获取数据');
    return;
  }
  
  // 添加节流逻辑，避免短时间内重复请求
  const now = Date.now();
  if (lastFetchTime && now - lastFetchTime < 30000) {
    console.log('请求过于频繁，跳过本次数据更新');
    return;
  }
  lastFetchTime = now;
  
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到有效的登录令牌');
    }
    
    // 使用设备的device_number作为deviceId
    const deviceNumber = currentDevice.value.device_number || currentDevice.value.id.toString();
    if (!deviceNumber) {
      throw new Error('无效的设备ID');
    }
    
    console.log(`正在获取设备 ${deviceNumber} 的实时数据...`);
    
    const response = await fetch(`https://penglink.pcwxcn.top/api/oil/data/${deviceNumber}?page=1&page_size=20`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`获取设备数据失败: ${response.status} ${response.statusText}`);
    }

    const result = await response.json();
    console.log('API返回数据:', result);
    
    if (result.code === 200) {
      // 检查数据结构
      if (result.data?.list?.length > 0) {
        const data = result.data.list[0];
        console.log('使用的数据(list形式):', data);
        console.log('数据字段列表:', Object.keys(data));
        
        // 检查是否包含ab字段
        const abFields = Object.keys(data).filter(key => key.startsWith('ab'));
        console.log('ab字段列表:', abFields);
        
        updateDeviceData(data);
        
        // 更新设备运行状态
        updateDeviceRunningStatus(data);
      } else if (Array.isArray(result.data) && result.data.length > 0) {
        // 如果数据直接是数组形式
        const data = result.data[0];
        console.log('使用的数据(数组形式):', data);
        console.log('数据字段列表:', Object.keys(data));
        
        // 检查是否包含ab字段
        const abFields = Object.keys(data).filter(key => key.startsWith('ab'));
        console.log('ab字段列表:', abFields);
        
        updateDeviceData(data);
        
        // 更新设备运行状态
        updateDeviceRunningStatus(data);
      } else {
        console.error('未找到有效数据结构');
        ElMessage.warning('未找到设备数据');
        clearAllData(); // 清空显示
      }
    } else {
      console.error(`API返回错误: ${result.message || '未知错误'}`);
      ElMessage.error(result.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取设备数据失败:', error);
    ElMessage.error(error.message || '获取设备数据失败');
    clearAllData(); // 出错时清空显示
  } finally {
    loading.value = false;
  }
}

// 监听设备变化
watch(currentDevice, (newDevice) => {
  console.log('设备变更:', newDevice)
  if (newDevice) {
    fetchDeviceData()
  } else {
    clearAllData()
  }
})

onMounted(() => {
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  if (currentDevice.value) {
    // 使用startDataUpdate函数统一管理定时器
    startDataUpdate()
  } else {
    // 如果没有当前设备，清除所有数据
    clearAllData()
  }
})

onUnmounted(() => {
  if (dataUpdateTimer) {
    clearInterval(dataUpdateTimer)
  }
})

// 数据字段映射
const dataFieldMap = {
  '油压': 'oil_pressure',
  '套压': 'casing_pressure',
  '井口温度': 'wellhead_temperature',
  '变频运行频率': 'variable_frequency_operation_frequency',
  '电机运行模式': 'motor_operating_mode',
  '变频故障状态': 'variable_frequency_fault_state',
  '电机功率因数': 'motor_power_factor',
  '冲程时间': 'stroke_time',
  '冲程位移': 'stroke_displacement',
  '冲程次数': 'stroke_count',
  '手动冲次设定值': 'manual_stroke_set_value',
  '自动调速泵效设定值': 'automatic_speed_pump_efficiency_set_value',
  '电机运行频率下限': 'lower_limit_of_motor_operating_frequency',
  '允许电机最大电流': 'maximum_allowable_motor_current',
  '动力设备运行状态': 'power_equipment_operation_status',
  '位移': 'displacement',
  '动力设备手/自动状态': 'power_equipment_manual_state',
  '动力设备启停控制': 'power_plant_start_stop_control',
  '动力设备启动报警延时时间': 'power_equipment_start_alarm_delay_time',
  '实时泵效': 'real_time_pumping_efficiency',
  '当天累计冲次': 'total_number_of_strokes_on_the_day',
  '当天耗电量': 'daily_power_consumption',
  '当天累计产液量': 'cumulative_fluid_production_for_the_day',
  '当天平均泵效': 'average_pump_efficiency_for_the_day',
  '吨液能耗': 'energy_consumption_per_ton_of_liquid',
  '预测液面值': 'forecasted_liquid_par_value',
  '最大载荷': 'maximum_load',
  '最小载荷': 'minimum_load',
  '上行最大电流': 'up_maximum_current',
  '下行最大电流': 'maximum_downgoing_current',
  '运行时长': 'running_time',
  '配重平衡度': 'balance_of_counterweight',
  '皮带打滑率': 'belt_slip_rate',
  '井液比重': 'fluid_specific_gravity',
  '井下压力': 'c1',
  '井下温度': 'c2',
  '流量计压力': 'c3',
  '瞬时气流量': 'c4',
  '累计气流量': 'c5',
  '变频参数': 'frequency_conversion_parameter',
  '频率控制方式': 'frequency_control_system',
  '电机实时有功功率': 'real_time_active_power_of_motor',
  '电机实时电流': 'motor_real_time_current',
  '电机实时电压': 'motor_real_time_voltage',
  '抽油机参数': 'pumping_unit_parameter',
  '冲次': 'jig_frequency',
  '冲程': 'stroke',
  '实际冲次': 'artwork_data_jig_frequency',
  '实际冲程': 'artwork_data_stroke',
  '功图数据': 'artwork_data',
  '功图实际点数': 'work_diagram_actual_number_of_points',
  '抽油机控制': 'pumping_unit_control',
  '空抽控制使能': 'the_air_exhaust_control_function_was_enabled',
  '间抽控制使能': 'the_intermittent_control_is_enabled',
  '间抽开机时间': 'time_to_switch_on',
  '间抽停机时间': 'alternate_downtime',
  '允许断电恢复自启动时间': 'allow_power_off_recovery_from_start_time'

}

// 油井运行数据
const oilWellData = ref([
  { label: '油压', value: '0.0', unit: 'MPa', icon: 'Odometer', color: '#409EFF' },
  { label: '套压', value: '0.0', unit: 'MPa', icon: 'TrendCharts', color: '#67C23A' },
  { label: '井口温度', value: '0.0', unit: '°C', icon: 'Timer', color: '#F56C6C' },
  { label: '井下压力', value: '0.0', unit: 'MPa', icon: 'Odometer', color: '#409EFF' },
  { label: '井下温度', value: '0.0', unit: '°C', icon: 'Timer', color: '#67C23A' },
  { label: '流量计压力', value: '0.0', unit: 'MPa', icon: 'Odometer', color: '#E6A23C' },
  { label: '瞬时气流量', value: '0.0', unit: 'm³/h', icon: 'DataBoard', color: '#F56C6C' },
  { label: '累计气流量', value: '0.0', unit: 'm³', icon: 'DataBoard', color: '#409EFF' },
  { label: '当前悬点载荷', value: '0.0', unit: 'KN', icon: 'Loading', color: '#67C23A' },
  { label: '位移', value: '0.0', unit: 'm', icon: 'Timer', color: '#E6A23C' },
  { label: '实时泵效', value: '0.0', unit: '%', icon: 'Odometer', color: '#F56C6C' },
  { label: '当天累计冲次', value: '0', unit: '次', icon: 'Timer', color: '#409EFF' },
  { label: '当天耗电量', value: '0', unit: 'KWH', icon: 'Monitor', color: '#67C23A' },
  { label: '当天累计产液量', value: '0.0', unit: 'M^3', icon: 'DataBoard', color: '#E6A23C' },
  {label: '最大载荷', value: '0.0', unit: 'KN', icon: 'Odometer', color: '#F56C6C' },
  {label:'最小载荷', value: '0.0', unit: 'KN', icon: 'Odometer', color: '#409EFF' },
  { label: '上行最大电流', value: '0.0', unit: 'A', icon: 'Connection', color: '#F56C6C' },
  { label: '下行最大电流', value: '0.0', unit: 'A', icon: 'Connection', color: '#409EFF' },
  { label: '运行时长', value: '0.0', unit: 'H', icon: 'Timer', color: '#67C23A' },
  { label: '配重平衡度', value: '0.0', unit: 'm', icon: 'Box', color: '#E6A23C' },
  { label: '皮带打滑率', value: '0.0', unit: '%', icon: 'PieChart', color: '#F56C6C' },
  { label: '井液比重', value: '0.0', unit: 'kg/m^3', icon: 'DataBoard', color: '#409EFF' },
  { label: '实际冲次', value: '0.0', unit: '次/min', icon: 'Timer', color: '#409EFF'  },
  { label: '实际冲程', value: '0.0', unit: 'm', icon: 'Timer', color: '#67C23A' }
]);

// 变频数据
const frequencyData = ref([
  //{ label: '电机运行模式', value: '工频', unit: '', icon: 'Setting', color: '#67C23A' },
  { label: '变频运行频率', value: '0.0', unit: 'Hz', icon: 'Connection', color: '#E6A23C' },
  { label: '变频故障状态', value: '正常', unit: '', icon: 'Warning', color: '#F56C6C' },
  { label: '电机功率因数', value: '0.0', unit: '', icon: 'Coin', color: '#409EFF' },
  { label: '电机实时有功功率', value: '0.0', unit: 'KW', icon: 'Monitor', color: '#67C23A' },
  { label: '电机实时电流', value: '0.0', unit: 'A', icon: 'Connection', color: '#E6A23C' },
  { label: '电机实时电压', value: '0.0', unit: 'VAC', icon: 'Connection', color: '#F56C6C' }
]);

// 抽油机数据
const pumpingUnitData = ref([
  { label: '冲次', value: '0.0', unit: '次/min', icon: 'Timer', color: '#409EFF' },
  { label: '冲程', value: '0.0', unit: 'm', icon: 'Timer', color: '#67C23A' },
 // { label: '功图采集时间', value: '无数据', unit: '', icon: 'Timer', color: '#E6A23C' }
]);

// 控制参数
const pumpingControlData = ref([
  { label: '空抽控制使能', value: '无', unit: '', icon: 'Setting', color: '#F56C6C' },
  { label: '空抽停机时间', value: '0.0', unit: 'min', icon: 'Timer', color: '#409EFF' },
  //{ label: '空抽停机时间手/智动设定', value: '手动', unit: '', icon: 'Setting', color: '#67C23A' },
  //{ label: '空抽停机时摆动运行', value: '无', unit: '', icon: 'Box', color: '#E6A23C' },
 // { label: '间抽控制使能', value: '无', unit: '', icon: 'Setting', color: '#F56C6C' },
 // { label: '间抽开机时间', value: '无数据', unit: '', icon: 'Timer', color: '#409EFF' },
  //{ label: '间抽停机时间', value: '无数据', unit: '', icon: 'Timer', color: '#67C23A' },
//  { label: '断电恢复自启动使能', value: '无', unit: '', icon: 'Setting', color: '#E6A23C' },
  { label: '允许断电恢复自启动时间', value: '0.0', unit: 'min', icon: 'Timer', color: '#F56C6C' },
 // { label: '手动冲次/自动冲次', value: '手动', unit: '', icon: 'Setting', color: '#409EFF' },
  { label: '手动冲次设定值', value: '0.0', unit: '次/min', icon: 'Timer', color: '#67C23A' },
  { label: '自动调速泵效设定值', value: '0.0', unit: '', icon: 'Odometer', color: '#E6A23C' },
  { label: '电机运行频率下限', value: '0.0', unit: 'Hz', icon: 'Connection', color: '#F56C6C' },
  { label: '允许电机最大电流', value: '0.0', unit: 'A', icon: 'Connection', color: '#409EFF' }
]);

// 更新设备运行状态的方法
const updateDeviceRunningStatus = (data) => {
  if (!data) {
    console.warn('无法更新设备运行状态: 数据为空');
    return;
  }
  
  // 检查是否存在动力设备运行状态字段
  const runningStatusField = dataFieldMap['动力设备运行状态'];
  let runningStatus = data[runningStatusField];
  let statusSource = '映射字段';
  
  console.log(`尝试从字段 ${runningStatusField} 获取运行状态: ${runningStatus}`);
  
  // 如果没有找到映射字段，尝试使用ab字段
  if (runningStatus === undefined) {
    statusSource = 'ab字段';
    // 尝试在ab字段中查找运行状态
    for (let i = 1; i <= 50; i++) {
      const abField = `ab${i}`;
      if (data[abField] !== undefined && (data[abField] === '0' || data[abField] === '1' || 
          data[abField] === 0 || data[abField] === 1)) {
        runningStatus = data[abField];
        console.log(`从字段 ${abField} 获取到运行状态: ${runningStatus}`);
        break;
      }
    }
  }
  
  // 将运行状态转换为文本
  let runningStatusText = '未知';
  if (runningStatus === '0' || runningStatus === 0) {
    runningStatusText = '停止';
  } else if (runningStatus === '1' || runningStatus === 1) {
    runningStatusText = '运行';
  }
  
  console.log(`设备运行状态(来源: ${statusSource}): ${runningStatus} -> ${runningStatusText}`);
  
  // 更新设备运行状态
  if (currentDevice.value) {
    // 检查状态是否有变化
    const oldStatus = currentDevice.value.runningStatus;
    
    if (oldStatus !== runningStatusText) {
      const updatedDevice = {
        ...currentDevice.value,
        runningStatus: runningStatusText
      };
      
      // 更新设备状态
      deviceStore.setCurrentDevice(updatedDevice);
      console.log(`设备运行状态已更新: ${oldStatus || '未知'} -> ${runningStatusText}`);
    } else {
      console.log(`设备运行状态未变化: ${runningStatusText}`);
    }
  } else {
    console.warn('无法更新设备运行状态: 当前设备为空');
  }
};

// 格式化数值显示
const formatValue = (label, value) => {
  // 检查值是否有效
  if (value === undefined || value === null || value === '') {
    if (label === '功图采集时间' || label.includes('时间')) {
      return '无数据';
    }
    return '0.000';
  }

  // 处理数值类型，根据原始数据的小数位数智能显示
  if (!isNaN(value) && typeof value !== 'boolean') {
    const numValue = parseFloat(value);
    if (!isNaN(numValue)) {
      // 检查原始值的小数位数
      const strValue = String(numValue);
      const decimalPart = strValue.split('.')[1];
      // 如果小数部分存在且长度大于等于3，则显示3位小数，否则保持原样
      if (decimalPart && decimalPart.length >= 3) {
        return numValue.toFixed(3);
      } else {
        return strValue; // 保持原始格式
      }
    }
  }

  // 如果不是数值类型，直接返回原值
  return value;
};


// 更新设备数据的方法
const updateDeviceData = (data) => {
  if (!data) return;
  
  console.log('数据对象键值:', Object.keys(data));
  
  // 检查是否有ab1字段并且包含JSON配置
  if (data.ab1 && typeof data.ab1 === 'string' && data.ab1.startsWith('[{')) {
    try {
      // 解析ab1字段中的JSON配置
      const configItems = JSON.parse(data.ab1);
      console.log('解析的配置项:', configItems);
      
      if (Array.isArray(configItems) && configItems.length > 0) {
        // 创建动态数据项数组
        const dynamicItems = configItems.map(config => {
          // 获取对应的ab字段值，确保使用正确的索引
          const fieldIndex = config.id % 50 || 1;
          const fieldName = `ab${fieldIndex}`;
          const fieldValue = data[fieldName];
          
          console.log(`映射字段 ${config.name} -> ${fieldName} = ${fieldValue}`);
          
          return {
            label: config.name,
            value: formatValue(config.name, fieldValue || '0.0'),
            unit: config.unit || '',
            icon: config.icon || 'DataLine',
            color: config.color || '#409EFF'
          };
        });
        
        // 更新油井运行数据，使用动态配置
        oilWellData.value = dynamicItems;
        
        // 清空其他数据组，因为现在使用动态配置
        frequencyData.value = [];
        pumpingUnitData.value = [];
        pumpingControlData.value = [];
        
        return; // 使用动态配置后直接返回
      }
    } catch (error) {
      console.error('解析ab1配置失败:', error);
      // 解析失败时继续使用默认逻辑
    }
  }
  
  // 以下是原有的逻辑，当没有动态配置时使用
  // 直接使用API返回的字段名称
  const useDirectFields = !data[dataFieldMap['油压']] && (data['ab1'] || data['device_name']);
  
  // 更新油井运行数据
  oilWellData.value = oilWellData.value.map((item, index) => {
    let value = '0.0';
    if (useDirectFields) {
      // 使用ab字段直接映射
      const abField = `ab${index + 1}`;
      if (data[abField] !== undefined && data[abField] !== '') {
        value = data[abField];
      }
    } else {
      // 使用映射字段
      // 对实时泵效数据特殊处理，乘以100
      if (item.label === '实时泵效') {
        const rawValue = data[dataFieldMap[item.label]] || '0.0';
        value = String(Number(rawValue) * 100);
      } else {
        value = data[dataFieldMap[item.label]] || '0.0';
      }
    }
    return {
      ...item,
      value: formatValue(item.label, value)
    };
  });

  // 更新变频数据
  frequencyData.value = frequencyData.value.map((item, index) => {
    let value = '0.0';
    if (useDirectFields) {
      // 使用ab字段直接映射，从油井数据之后开始
      const abField = `ab${oilWellData.value.length + index + 1}`;
      if (data[abField] !== undefined && data[abField] !== '') {
        value = data[abField];
      }
    } else {
      // 使用映射字段
      value = data[dataFieldMap[item.label]] || 
        (item.label === '变频故障状态' ? 
          (data[dataFieldMap[item.label]] > 0 ? `故障(${data[dataFieldMap[item.label]]})` : '正常') : 
         item.label === '电机运行模式' ? '工频' : 
         item.label === '动力设备运行状态' ? 
          (data[dataFieldMap[item.label]] == 1 ? '运行' : '停止') : 
         '0.0');
    }
    return {
      ...item,
      value: formatValue(item.label, value)
    };
  });

  // 更新抽油机数据
  pumpingUnitData.value = pumpingUnitData.value.map((item, index) => {
    let value = '0.0';
    if (useDirectFields) {
      // 使用ab字段直接映射，从油井数据和变频数据之后开始
      const abField = `ab${oilWellData.value.length + frequencyData.value.length + index + 1}`;
      if (data[abField] !== undefined && data[abField] !== '') {
        value = data[abField];
      }
    } else {
      // 使用映射字段
      // 对实时泵效数据特殊处理，乘以100
      if (item.label === '实时泵效') {
        const rawValue = data[dataFieldMap[item.label]] || '0.0';
        value = String(Number(rawValue) * 100);
      } else {
        value = data[dataFieldMap[item.label]] || '0.0';
      }
    }
    return {
      ...item,
      value: formatValue(item.label, value)
    };
  });

  // 更新控制参数
  pumpingControlData.value = pumpingControlData.value.map((item, index) => {
    let value = '0.0';
    if (useDirectFields) {
      // 使用ab字段直接映射，从前面所有数据之后开始
      const abField = `ab${oilWellData.value.length + frequencyData.value.length + pumpingUnitData.value.length + index + 1}`;
      if (data[abField] !== undefined && data[abField] !== '') {
        value = data[abField];
      }
    } else {
      // 使用映射字段
      // 对实时泵效数据特殊处理，乘以100
      if (item.label === '实时泵效') {
        const rawValue = data[dataFieldMap[item.label]] || '0.0';
        value = String(Number(rawValue) * 100);
      } else {
        value = data[dataFieldMap[item.label]] || '0.0';
      }
    }
    return {
      ...item,
      value: formatValue(item.label, value)
    };
  });
};

// 使用上面定义的formatValue函数
</script>

<style scoped>
.real-time-panel {
  height: 100%;
  padding: 0;
  background: var(--el-bg-color);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-bottom: 1px solid #EBEEF5;
}

.panel-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-button) {
  padding: 4px 12px;
  height: 24px;
  font-size: 12px;
}

:deep(.el-icon) {
  font-size: 12px;
}

.data-grid {
  padding: 8px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.data-grid {
  display: grid;
  gap: 12px;
  height: 100%;
  overflow-y: auto;
  grid-template-columns: repeat(4, 1fr);
}

.data-group {
  background: var(--el-bg-color-overlay);
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.data-group:hover {
  transform: translateY(-2px);
}

.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.group-header .el-icon {
  margin-right: 6px;
  font-size: 16px;
  color: var(--el-color-primary);
  filter: drop-shadow(0 2px 2px rgba(0, 0, 0, 0.1));
}

.group-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.data-items {
  display: grid;
  gap: 6px;
  grid-template-columns: 1fr;
}

.data-item {
  display: flex;
  align-items: center;
  padding: 8px 10px;
  background: var(--el-bg-color);
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 0;
  max-width: 280px;
  box-shadow: 
    0 2px 4px rgba(0, 0, 0, 0.05),
    0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.data-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 50%;
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0.1),
    rgba(255, 255, 255, 0)
  );
  border-radius: 4px 4px 0 0;
}

.data-item:hover {
  transform: translateY(-1px) scale(1.02);
  box-shadow: 
    0 4px 8px rgba(0, 0, 0, 0.08),
    0 2px 4px rgba(0, 0, 0, 0.12);
}

.item-content {
  margin-left: 8px;
  flex: 1;
  min-width: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
  position: relative;
  z-index: 1;
}

.item-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-value {
  font-size: 13px;
  color: var(--el-text-color-primary);
  font-weight: 500;
  white-space: nowrap;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}

.unit {
  font-size: 11px;
  color: var(--el-text-color-secondary);
  margin-left: 2px;
}

@media (max-width: 1919px) {
  .data-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .data-items {
    grid-template-columns: repeat(2, 1fr);
  }

  .data-item {
    max-width: 240px;
  }
}

@media (max-width: 1440px) {
  .data-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .data-items {
    grid-template-columns: repeat(2, 1fr);
  }

  .data-item {
    max-width: 220px;
  }
}

@media (max-width: 1200px) {
  .data-grid {
    grid-template-columns: 1fr;
  }
  
  .data-items {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .data-items {
    grid-template-columns: 1fr;
  }
}
</style>